package com.sdry.service.impl.llm;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.transaction.interceptor.TransactionAspectSupport;

import com.sdry.mapper.llm.ClassesMapper;
import com.sdry.mapper.llm.EmployeeMapper;
import com.sdry.mapper.llm.EmployeeRecordMapper;
import com.sdry.mapper.llm.TeamMapper;
import com.sdry.mapper.llm.TeamRecordMapper;
import com.sdry.mapper.llm.UserMapper;
import com.sdry.model.jyy.Shedudetail;
import com.sdry.model.llm.Classes;
import com.sdry.model.llm.EmployeeRecord;
import com.sdry.model.llm.Team;
import com.sdry.model.llm.TeamRecord;
import com.sdry.model.llm.User;
import com.sdry.service.llm.TeamRecordService;

/** 
* @author lian 
* @version 1.0
* @time 2018年10月17日 下午3:47:09
*/

@Service
public class TeamRecordServiceImp implements TeamRecordService {

	/**
	 * 注入班组记录mapper
	 */
	@Resource
	private TeamRecordMapper teamRecordMapper; 
	/**
	 * 注入班组记录mapper
	 */
	@Resource
	private EmployeeRecordMapper employeeRecordMapper;  
	/**
	 * 注入员工管理的mapper
	 */
	@Resource
	private EmployeeMapper empMapper;  
	/**
	 * 注入班组的mapper
	 */
	@Resource
	private TeamMapper teamMapper;  
	/**
	 * 注入用户的mapper
	 */
	@Resource
	private UserMapper userMapper; 
	/**
	 * 注入班次的mapper
	 */
	@Resource
	private ClassesMapper classesMapper; 
	
	/**
	 * 查询班组记录总行数
	 * @param teamRecord 班组记录
	 * @return
	 */
	@Override
	public int countTeamRecord(TeamRecord teamRecord) {
		return teamRecordMapper.countTeamRecord(teamRecord);
	}

	/**
	 * 分页查询班组记录
	 * @param map 
	 * @return
	 */
	@Override
	public List<TeamRecord> listPageTeamRecord(Map<String, Object> map) {
		return teamRecordMapper.listPageTeamRecord(map);
	}	

	/**
	 * 新增班组记录
	 * @param teamRecord 班组记录
	 * @return
	 */
	@Override
	public int insertTeamRecord(TeamRecord teamRecord, HttpSession session)throws Exception {
		int isSuccess = 0;
		/*第一步，存班组记录（班组编号，排产单ID） */
		//获取登录的用户信息
		User user = (User)session.getAttribute("currentUser");
		//根据登陆的信息获取员工表中对应的班组信息
		Team newTeam = (Team)session.getAttribute("team");
		if(null != newTeam){
			//1、把班组ID存入班组记录（根据员工ID查出所属班组ID）
			teamRecord.setTeamId(newTeam.getTid());;
			Date data = new Date();
			SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
			String time = sdf.format(data);
			List<Classes> classesByWrite = classesMapper.getClassesByName("白班");
			Classes clas = classesByWrite.get(0);
			//白班的开始时间（小时） 
			Integer startTime = Integer.parseInt(clas.getStartTime().substring(0,2));
			//当天的小时
			Integer hourse = Integer.parseInt(time.substring(11, 13));
			//如果登录时间小于当天的白班的开始时间，则记录上一天
			if(hourse < startTime){
				Calendar ca = Calendar.getInstance();//得到一个Calendar的实例 
				ca.setTime(data); //设置时间为当前时间
				ca.add(Calendar.DATE, -1);
				Date last = ca.getTime();
				time = sdf.format(last);
			}
			//2、把日期存入班组记录
			teamRecord.setTtime(time.substring(0, 10));
			//3、把班次存入班组记录
			Team t2 = teamMapper.getTeamByTid(newTeam.getTid());
			teamRecord.setRemark01(t2.getCrew());
			session.setAttribute("team", t2);
			//根据班次查询工作时间
			List<Classes> classesByName = classesMapper.getClassesByName(t2.getCrew());
			Classes cla = classesByName.get(0);
			//4、把开始时间存入班组记录
			teamRecord.setRemark02(cla.getStartTime());
			//5、把结束时间存入班组记录
			teamRecord.setRemark03(cla.getEndTime());
			//6、查看是否有班组记录（根据班组ID和日期）
			TeamRecord tempTeamRecord = teamRecordMapper.getTeamRecordByTeamRecord(teamRecord);
			if(null != tempTeamRecord){
				//修改班组记录的排产单ID
				isSuccess = teamRecordMapper.updateTeamRecord(tempTeamRecord);
			}else{
				//保存班组记录（班组ID，日期， 排产单ID）
				isSuccess = teamRecordMapper.insertTeamRecord(teamRecord);
			}
			/*第二步，保存班组对应的员工记录（工号，班组记录ID， 登录时间） */
			if(isSuccess > 0){
				//获取当前班组记录的ID
				TeamRecord newTeamRecord = teamRecordMapper.getTeamRecordByTeamRecord(teamRecord);
				//判断是否有员工记录
				EmployeeRecord employeeRecord = new EmployeeRecord();
				employeeRecord.setTid(newTeamRecord.getTid());
				employeeRecord.setLoginTime(time.substring(0,10));
				employeeRecord.setUid(user.getUid());
				EmployeeRecord temp2 = employeeRecordMapper.getEmployeeRecordByEmployeeRecord(employeeRecord);
				//如果没有记录就保存记录
				if(null == temp2){
					//把班组记录的ID存入员工记录（employeeRecords）的表中
					employeeRecord.setTid(newTeamRecord.getTid());
					//把班组长登录的时间存入员工记录
					SimpleDateFormat sdf2 = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
					String loginTime = sdf2.format(data);
					employeeRecord.setLoginTime(loginTime);
					//把班组长的ID存入员工记录
					employeeRecord.setUid(user.getUid());
					//把班组长存入员工记录的备注（首次登录肯定是班组长）
					employeeRecord.setRemark01("班组长");
					isSuccess = employeeRecordMapper.saveEmployeeRecord(employeeRecord);
					//把员工记录的ID存入session（退出时，根据这个ID修改退出时间）
					session.setAttribute("employeeRecordId", isSuccess);
				}
			}
		}
		return isSuccess;
	}

	/**
	 * 修改班组记录
	 * @param teamRecord 班组记录
	 * @return
	 */
	@Override
	public int updateTeamRecord(TeamRecord teamRecord) {
		//先根据ID查询原记录
//		TeamRecord t = teamRecordMapper.findById(teamRecord.getTid());
		//存入新的数据库表中
//		int i = teamRecordMapper.saveTeamRecordInCopy(t);
		//修改数据
		return teamRecordMapper.updateTeamRecord(teamRecord);
	}

	/**
	 * 删除班组记录
	 * @param str 班组记录ID字符串
	 * @return
	 */
	@Transactional(rollbackFor={Exception.class})
	public int deleteTeamRecord(String str) {
		int isSuccess = 0;
		String[] split = str.split(",");
		try {
			for (String rid : split) {
				isSuccess = teamRecordMapper.deleteTeamRecord(Long.parseLong(rid));
			}
		}catch (
		Exception e) {
			e.printStackTrace();
			TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
		}
		return isSuccess;
	}

	/**
	 * 修改班组记录(暂不用)
	 * @param position 工位
	 * @param request 请求
	 * @return
	 */
	@Override
	public int updateTeamRecordToPosition(String position, HttpServletRequest request) {
		int isSuccess = 0;
		/*User user = (User)request.getSession().getAttribute("currentUser");
		//根据登陆的信息获取员工表中对应的班组信息
		Employee employee = empMapper.findByUid(user.getUid());
		Date data = new Date();
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
		String time = sdf.format(data);
		TeamRecord tr = new TeamRecord();
		//把班组名称加到班组记录中
		tr.setTname(employee.getTeamName());
		Team team = teamMapper.getTeamByTid(employee.getTid());
		//把班组编号加到班组记录中
		tr.setTnumber(team.getTnumber());
		//把日期加到班组记录中
		tr.setTtime(time);
		//在班组记录中查询是班组长是否选择了排产单
		List<TeamRecord> teamRecords = teamRecordMapper.findTeamRecordByTeamAndData(tr);
		if(null != teamRecord){
			//把员工姓名和工位追加到班组人员的数据后面
			teamRecord.setPname(teamRecord.getPname()+","+user.getUserName()+"("+position+")");
			updateTeamRecord(teamRecord);
		}else{
			isSuccess = -1;
		}*/
		
		return isSuccess;
	}

	/**
	 * 分页查询班组长选择的排产单
	 * @param map
	 * @return
	 * @see com.sdry.service.llm.TeamRecordService#listPageShedudetail(java.util.Map)
	 */
	@Override
	public List<Shedudetail> listPageShedudetail(Map<String, Object> map) {
		Integer limit = (Integer)map.get("limit");
		Integer page = (Integer)map.get("page");
		String productionId = (String)map.get("productionId");
		String[] split = productionId.split(",");
		if(split.length == 0){
			return null;
		}else{
			int max = split.length;
			if(max > page*limit){
				max = page*limit;
			}
			List<Shedudetail> list = new ArrayList<>();
			for(int i = (page-1)*limit; i < max; i++){
				Long id = Long.parseLong(split[i]);
				Shedudetail shedudetail = teamRecordMapper.getShedudetailById(id);
				list.add(shedudetail);
			}
			return list;
		}
	}

	/**
	 * 班组长选择的排产单的总数
	 * @param teamRecord
	 * @return
	 * @see com.sdry.service.llm.TeamRecordService#countShedudetail(com.sdry.model.llm.TeamRecord)
	 */
	@Override
	public int countShedudetail(TeamRecord teamRecord) {
		int isSuccess = 0;
		String str = teamRecord.getProductionId();
		String[] split = str.split(",");
		isSuccess = split.length;
		return isSuccess;
	}

	/**
	 * 删除班组长选定的排产单
	 * @param pid 排产单ID
	 * @param tid 班组记录ID
	 * @return
	 * @see com.sdry.service.llm.TeamRecordService#deleteTeamRecordOfPid(java.lang.Long)
	 */
	@Override
	public int deleteTeamRecordOfPid(Long tid, Long pid) {
		int isSuccess = 0;
		//1、取值
		TeamRecord teamRecord = teamRecordMapper.getTeamRecordByTid(tid);
		String pids = teamRecord.getProductionId();
		//2、分解，遍历，删除元素
		String[] split = pids.split(",");
		List<String> list = new ArrayList<>();
		for(int i = 0; i < split.length; i ++){
			list.add(split[i]);
		}
		list.remove(pid+"");
		//3、把修改后的数据存入数据库
		String str = list.toString();
		String str2 = str.replaceAll(" ", "");
		pids = str2.substring(1, str2.length()-1);
		teamRecord.setProductionId(pids);
		isSuccess = teamRecordMapper.updateTeamRecord(teamRecord);
		return isSuccess;
	}

	/**
	 * 校验是否删除班组记录
	 * @param str
	 * @return
	 */
	@Override
	public int deleteTeamRecordOfVerify(String str) {
		int isSuccess = -1;
		String[] split = str.split(",");
		EmployeeRecord employeeRecord = new EmployeeRecord();
		for(int i = 0; i < split.length; i ++){
			Long id = Long.parseLong(split[i]);
			employeeRecord.setTid(id);
			//根据班组记录ID查找员工记录的数量
			int ids = employeeRecordMapper.countEmployeeRecordByTid(employeeRecord);
			//获取排产单的个数
			TeamRecord tr = teamRecordMapper.findById(id);
			String string = tr.getProductionId();
			String[] prositionIds = string.split(",");
			//如果有员工记录或是有排产单
			if(ids > 0 || prositionIds.length > 0){
				isSuccess = 1;
				break;
			}
		}
		return isSuccess;
	}

	/**      
	 * 修改已选排产单 
	 * @param teamRecord
	 * @param session
	 * @return    
	 */
	@Override
	public int updateTeamRecordOnPositionId(TeamRecord teamRecord, HttpSession session) {
		int isSuccess = 0;
		if(null != teamRecord.getProductionId() && !"".equals(teamRecord.getProductionId())){
			//1、根据登陆的信息获取员工表中对应的班组信息
			Team newTeam = (Team)session.getAttribute("team");
			if(null != newTeam){
				Long tid = newTeam.getTid();
				Date date = new Date();
				SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
				String time = sdf.format(date);
				TeamRecord temp = new TeamRecord();
				temp.setTtime(time);
				temp.setTeamId(tid);
				//2、查看是否有班组记录（根据班组ID和日期）
				TeamRecord tempTeamRecord = teamRecordMapper.getTeamRecordByTeamRecord(temp);
				if(null != tempTeamRecord){
					//3、把班组记录中的排产单ID修改为新的排产单ID
					tempTeamRecord.setProductionId(teamRecord.getProductionId());
					isSuccess = teamRecordMapper.updateTeamRecord(tempTeamRecord);
				}
			}
		}
		return isSuccess;
	}

	/**  
	 * 查询当天班组记录     
	 * @param teamRecord
	 * @param session
	 * @return    
	 */
	@Override
	public int getTeamRecordByTime(TeamRecord teamRecord, HttpSession session) {
		int isSuccess = 0;
		//1、根据登陆的信息获取员工表中对应的班组信息
		Team newTeam = (Team)session.getAttribute("team");
		if(null != newTeam){
			Long tid = newTeam.getTid();
			Date date = new Date();
			SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:dd");
			String time = sdf.format(date);
			List<Classes> classesByWrite = classesMapper.getClassesByName("白班");
			Classes clas = classesByWrite.get(0);
			//白班的开始时间（小时） 
			Integer startTime = Integer.parseInt(clas.getStartTime().substring(0,2));
			//当天的小时
			Integer hourse = Integer.parseInt(time.substring(11, 13));
			//如果登录时间小于当天的白班的开始时间，则记录上一天
			if(hourse < startTime){
				Calendar ca = Calendar.getInstance();//得到一个Calendar的实例 
				ca.setTime(date); //设置时间为当前时间
				ca.add(Calendar.DATE, -1);
				Date last = ca.getTime();
				time = sdf.format(last);
			}
			TeamRecord temp = new TeamRecord();
			time = time.substring(0, 10);
			temp.setTtime(time);
			temp.setTeamId(tid);
			//2、查看是否有班组记录（根据班组ID和日期）
			TeamRecord tempTeamRecord = teamRecordMapper.getTeamRecordByTeamRecord(temp);
			if(null != tempTeamRecord){
				isSuccess = 1;
			}else{
				//3、查看当天其他班组是否选过排产单
				List<TeamRecord> list = teamRecordMapper.getTeamRecordByTime(time);
				//3.1如果其他班组已经选过
				if(list.size() > 0){
					for(TeamRecord t : list){
						//3.2如果两个班组选择不是同一个排产单
						if(!t.getProductionId().equals(teamRecord.getProductionId())){
							isSuccess = 3;
						}
					}
				}
			}
		}else{
			isSuccess = 2;
		}
		return isSuccess;
	}

	/**       
	 * 根据班组ID和日期查询班组记录
	 * @param tid
	 * @param today
	 * @return    
	 */
	@Override
	public TeamRecord getTeamRecordByTeamAndTime(Long tid, String today) {
		TeamRecord teamRecord = new TeamRecord();
		teamRecord.setTeamId(tid);
		teamRecord.setTtime(today.substring(0,11));
		return teamRecordMapper.getTeamRecordByTeamRecord(teamRecord);
	}

	/**       
	 * @param parseInt
	 * @return    
	 */
	@Override
	public Shedudetail selectByPrimaryKey(int parseInt) {
		return teamRecordMapper.getShedudetailById(parseInt+0L);
	}

}
